import os
import re

# 原始文件夹路径
original_folder = r'D:\BaiduNetdiskDownload\M4x100IMF\Annotations'
# 新的文件夹路径
new_folder = r'C:\Users\Y07\Desktop\yolov8-pytorch-master\VOCdevkit\VOC2007\Annotations'

# 正则表达式匹配XML中的<folder>标签
folder_pattern = re.compile(r'<folder>(.*?)</folder>', re.IGNORECASE)

# 读取文件内容的函数
def read_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        return file.read()

# 写入文件内容的函数
def write_file(file_path, content):
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(content)

# 替换<folder>标签内容的函数
def replace_folder_tag(content, old_folder, new_folder):
    return folder_pattern.sub(f'<folder>{new_folder}</folder>', content)

# 处理单个文件
def process_file(file_path):
    content = read_file(file_path)
    new_content = replace_folder_tag(content, original_folder, new_folder)
    write_file(file_path, new_content)
    print(f'Processed file: {file_path}')

# 处理文件夹内的所有文件
def process_folder(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.xml'):
                file_path = os.path.join(root, file)
                process_file(file_path)

# 指定要处理的文件夹路径
folder_path = '"D:\BaiduNetdiskDownload\M4x100IMF\Annotations"'  # 请替换为你的XML文件所在的文件夹路径
process_folder(folder_path)